<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="handleSearch"
        @reset="handleReset"
      />
    </Container>
    <Container
      height="fill"
      :scroll-y="true"
      display="flexY"
      style="position: relative"
    >
      <OperationContainer
        style="margin-bottom: 10px; display: flex; align-items: center"
      >
        <div><Button icon="add" @click="createNewData">新增</Button></div>
        <!-- <div><Button icon="delete" @click="createNewData">删除</Button></div> -->
      </OperationContainer>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
        header-row-class-name="ck-table-header"
        row-class-name="ck-table-row"
        size="small"
        height="100%"
      >
        <el-table-column align="center" type="index" label="" width="60" />
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column label="科室编码" prop="deptCode">
          <!-- <template slot-scope="scope">
            <div class="text-btn" @click="handleDept(scope.row)">
              {{
                scope.row.deptCode === "AAAAAAAAAA"
                  ? "9999"
                  : scope.row.deptCode
              }}
            </div>
          </template> -->
        </el-table-column>

        <el-table-column prop="deptName" label="科室名称" />
        <el-table-column prop="costItemCode" label="成本编码" />
        <el-table-column prop="costItemName" label="成本名称" />
        <el-table-column label="金额">
          <template v-slot="scope">
            {{ scope.row.amount && scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="accountName" label="会计分类" />
        <el-table-column prop="deptTypeName" label="科室分类" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <i
              v-if="scope.row.extraE == 1"
              class="el-icon-edit-outline"
              style="
                padding-top: 4px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="handleEdit(scope.row)"
            />
            <i
              v-if="scope.row.extraE == 1"
              class="el-icon-delete"
              style="
                padding-top: 4px;
                padding-left: 10px;
                font-size: 20px;
                color: #207efa;
                cursor: pointer;
              "
              @click="handleDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 合计 -->
      <div class="tb-hj">总额：{{ amount }}</div>
      <!-- 分页 -->
      <Pagination
        :total="pageAttr.total"
        :page="pageAttr.currentPage"
        :page-size="pageAttr.pageSize"
        @pagation="pagationChange"
      />
    </Container>

    <Container>
      <Dialog
        :title="title"
        :visible="showEidtVlidate"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="drawClose"
        @confirm="handleConfirm"
      >
        <el-form ref="form" :model="formInfo" label-width="80px" size="small">
          <el-row>
            <el-col :span="12">
              <el-form-item label="科室名称">
                <el-select
                  v-model="formInfo.deptCode"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in filterElements[2].options"
                    :key="item.deptCode"
                    :label="item.deptName"
                    :value="item.deptCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成本名称">
                <el-select
                  v-model="formInfo.costItemCode"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in costNameList"
                    :key="item.edCode"
                    :label="item.edName"
                    :value="item.edCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="科室分类">
                <el-select
                  v-model="formInfo.deptTypeId"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in filterElements[1].options"
                    :key="item.edCode"
                    :label="item.edName"
                    :value="item.edCode"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="日期">
                <el-date-picker
                  v-model="formInfo.time"
                  type="date"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="金额">
                <el-input v-model="formInfo.amount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="摘要">
                <el-input v-model="formInfo.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </Dialog>
    </Container>
  </ContainerGroup>
</template>

<script>
import {
  getEnumDetailSource,
  getDepartmentSource,
} from "../../../utils/apis/accountingUnit/dept";

import { listBaseCost } from "../../../utils/apis/dataExchange/index";
import { BasicParams } from "../../../utils/basicParams";
import projectId from "../../../utils/apis/projectId";
import { CostData } from "@/utils/basicSetting/costData";
import {
  addBaseCost,
  deleteBaseCost,
} from "../../../utils/apis/accountingUnit/share.js";
// import {
//   getEnumDetailSource,
// } from "../../../utils/apis/accountingUnit/factor";
export default {
  name: "Wage", // 科室-工资对应
  components: {},
  data() {
    return {
      costNameList: [],
      formInfo: {
        time: "",
        deptCode: "",
        deptName: "",
        amount: "",
        costItemCode: "",
        costItemName: "",
        deptTypeId: "",
        deptTypeName: "",
        remark: "",
      },
      amount: 0,
      loading: false,
      showEidtVlidate: false,
      title: "",
      filterElements: [
        {
          key: "yearMonth",
          type: "date-picker",
          label: "年/月",
          mode: "month",
          type: "date-picker",
          format: "yyyy-MM",
          value: this.$util.currentDate(),
          width: 210,
        },

        {
          filterable: true,
          clearable: true,
          key: "deptTypeId",
          type: "Select",
          label: "科室分类",
          value: "",
          width: 210,
          itemLabel: "edName",
          itemValue: "edCode",
          options: [],
          change: this.hanldeChangeSelect,
        },
        {
          filterable: true,
          clearable: true,
          key: "lstDept",
          type: "Select",
          label: "科室",
          value: "",
          multiple: true,
          collapseTags: true,
          itemLabel: "deptName",
          itemValue: "deptCode",
          width: 210,
          options: [],
        },
        {
          filterable: true,
          clearable: true,
          key: "unitCode",
          type: "Select",
          label: "会计分类",
          value: "",
          itemLabel: "edName",
          itemValue: "edCode",
          width: 210,
          options: [],
        },
        {
          clearable: true,
          filterable: true,
          key: "linkFlag",
          type: "Select",
          label: "是否关联",
          value: "",
          width: 210,
          itemLabel: "label",
          itemValue: "value",
          options: [
            {
              label: "已关联",
              value: "1",
            },
            {
              label: "未关联",
              value: "0",
            },
          ],
        },
      ],
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
      },
      tableData: [],
      tableLoading: false,
      newParamList: {},
      oldTime: "",
    };
  },
  created() {
    this.getHsSelect();
  },
  mounted() {},
  methods: {
    handleDelete(row) {
      //删除
      this.$confirm({
        title: "温馨提示",
        content: "您确定要删除该条数据?",
        okText: "确定",
        cancelText: "取消",
        okFn: () => {
          deleteBaseCost(row.id, row.year).then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message);
              this.pageAttr.currentPage = 1;
              this.getData();
            } else {
              this.$message.error(res.data.message);
            }
          });
        },
        cancelFn: () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        },
      });
    },
    handleClearForm() {
      //清除新增/编辑form
      this.formInfo.deptCode = "";
      this.formInfo.deptTypeId = "";
      this.formInfo.costItemCode = "";
      this.formInfo.amount = "";
      this.formInfo.time = "";
      this.oldTime = "";
      this.formInfo.remark = "";
    },
    handleEdit(row) {
      this.handleClearForm();
      this.rowId = row.id;
      this.title = "编辑成本数据";
      this.showEidtVlidate = true;
      this.setDetails(row);
    },
    setDetails(result) {
      this.formInfo.deptCode = result.deptCode;
      this.formInfo.deptTypeId = result.deptTypeId;
      this.formInfo.costItemCode = result.costItemCode;
      this.formInfo.amount = result.amount;
      this.formInfo.time = result.time;
      this.oldTime = result.time;
      this.formInfo.remark = result.extraB;
    },
    handleConfirm() {
      //确定
      if (!this.formInfo.deptCode) {
        this.$message.warning("请选择科室");
        return;
      }
      if (!this.formInfo.deptTypeId) {
        this.$message.warning("请选择科室分类");
        return;
      }
      const param = {
        deptCode: this.formInfo.deptCode,
        deptName: this.filterElements[2].options.find(
          (item) => item.deptCode === this.formInfo.deptCode
        )?.deptName,
        deptTypeId: this.formInfo.deptTypeId,
        deptTypeName: this.filterElements[1].options.find(
          (item) => item.edCode === this.formInfo.deptTypeId
        )?.edName,
        costItemCode: this.formInfo.costItemCode,
        costItemName: this.costNameList.find(
          (item) => item.edCode === this.formInfo.costItemCode
        )?.edName,
        amount: this.formInfo.amount,
        time: this.formInfo.time,
        remark: this.formInfo.remark,
      };
      if (this.title == "编辑成本数据") {
        param.oldTime = this.oldTime;
        param.id = this.rowId;
      }
      addBaseCost(param).then((res) => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message);
          this.showEidtVlidate = false;
          //this.getYearMonthList();
          this.getData();
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 分页
    pagationChange(payload) {
      console.log("payload", payload);
      this.pageAttr.currentPage = payload.page;
      this.pageAttr.pageSize = payload.pageSize;
      this.getData();
    },
    getData() {
      // let curMonthLastDay = new Date(
      //   this.newParamList.yearMonth &&
      //     this.newParamList.yearMonth.split("-")[0],
      //   this.newParamList.yearMonth &&
      //     this.newParamList.yearMonth.split("-")[1],
      //   0
      // );
      // 列表
      let costData = new CostData();
      costData.year =
        this.newParamList.yearMonth &&
        this.newParamList.yearMonth.split("-")[0];
      costData.month =
        this.newParamList.yearMonth &&
        parseInt(this.newParamList.yearMonth.split("-")[1]);
      costData.deptTypeId = this.newParamList.deptTypeId || "";
      costData.lstDept = this.newParamList.lstDept || [];
      costData.unitCode = this.newParamList.unitCode || "";
      costData.pageIndex = this.pageAttr.currentPage;
      costData.pageSize = this.pageAttr.pageSize;
      costData.linkFlag = this.newParamList.linkFlag || "";
      this.tableLoading = true;
      listBaseCost(costData).then((res) => {
        if (res.data.code === 200) {
          this.tableLoading = false;
          this.tableData = res.data.data.data.list;
          this.amount = this.fmoney(res.data.data.amount, 2);
          this.pageAttr.total = res.data.data.data.total || 0;
        } else {
          this.tableLoading = false;
        }
      });
    },
    fmoney(s, n) {
      n = n > 0 && n <= 20 ? n : 2;
      s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
      var l = s
          .split(".")[0]
          .split("")
          .reverse(),
        r = s.split(".")[1];
      let t = "";
      for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
      }
      return (
        t
          .split("")
          .reverse()
          .join("") +
        "." +
        r
      );
    },
    hanldeChangeSelect(value) {
      if (!value) {
        this.$refs.filterForm.handleForceSet({
          lstDept: [],
        });
      }
      this.handleZt(value);
    },
    handleZt(value) {
      //科室
      let params = {
        projectId: projectId.project,
        deptTypeId: value,
      };
      getDepartmentSource(params).then((res) => {
        if (res.data.code === 200) {
          this.filterElements[2].options = res.data.data.filter(
            (item) => item.clinicalPropertyId != ""
          );
        }
      });
    },
    getHsSelect() {
      // 科室分类
      let basicParams = new BasicParams();
      basicParams.edParentCode = "BD_DepartCategory";
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          this.filterElements[1].options = res.data.data;
        }
      });
      //会计分类
      basicParams.edParentCode = "BD_AccountSubject";
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          this.filterElements[3].options = res.data.data;
        }
      });
      //科室
      getDepartmentSource({
        projectId: "1",
        SysId: "Cost",
      }).then((res) => {
        if (res.data.code === 200) {
          this.filterElements[2].options = res.data.data;
        }
      });
      //成本名称
      basicParams.edParentCode = "CostItem";
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          this.costNameList = res.data.data;
        }
      });
    },
    createNewData() {
      this.handleClearForm();
      this.showEidtVlidate = true;
      this.title = "新增成本数据";
    },
    saveEidtRule() {},
    drawClose() {
      this.showEidtVlidate = false;
    },
    handleSearch(value) {
      this.newParamList = value;
      this.pageAttr.currentPage = 1;
      this.getData();
    },
    handleReset() {
      location.reload();
    },
  },
};
</script>

<style lang="less" scoped>
.tb-hj {
  height: 37px;
  // border: 1px solid #ebeef5;
  position: absolute;
  bottom: 18px;
}
.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}
.pagenation-box {
  display: flex;
  padding-top: 2px;
  justify-content: flex-end;
}
</style>
